﻿#include <QByteArray>
#include <QDebug>
#include <QMessageBox>
#include <QString>

#include "config.h"
#include "memcached.h"
#include<qtextcodec.h>
MemCached* MemCached::instance = NULL;

MemCached::MemCached()
{


    QTextCodec* code=QTextCodec::codecForName("utf-8");

    QTextCodec::setCodecForLocale(code);
    memcached = memcached_create(NULL);

    QString strIp = GYSCADAConfig::getInstance()->getGyscadaIp();
    QByteArray byteArrayIp = strIp.toLatin1();
    const char* ip = byteArrayIp.data();
    int port = GYSCADAConfig::getInstance()->getGyscadaPort();

    if (memcached != NULL && memcached_server_add(memcached, ip, port) != MEMCACHED_SUCCESS) {
        memcached_free(memcached);
        memcached = NULL;
    }

    if (memcached == NULL) {
        QMessageBox::critical(NULL, QObject::tr("Error"), QObject::tr("Can't connect data base server"));
    }
}

MemCached::~MemCached()
{
    memcached_free(memcached);
}

MemCached* MemCached::getInstance()
{
    if (MemCached::instance == NULL) {
        MemCached::instance = new MemCached;
    }

    return MemCached::instance;
}

double MemCached::getValue(const QString &key, bool* ok)
{
    if (memcached == NULL) {
        *ok = false;
        return 0;
    } else {
        uint32_t            flags;
        size_t              value_length;
        QByteArray          byteKey = key.toLatin1();
        memcached_return    error = MEMCACHED_SUCCESS;
        char*               memcachedKey = byteKey.data();
        char*               value = memcached_get(memcached, memcachedKey, strlen(memcachedKey), &value_length, &flags, &error);

        if (value != NULL) {
            *ok = true;
            return *(double*)value;
        } else {
            *ok = false;
            return 0;
        }
    }
}
